#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "chatclientwindow.h"
#include <QString>
#include <QSocketDescriptor>
#include <tcpserver.h>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_tcpServer = new TCPServer();
    chat_model = new QStringListModel(this);

    QFont label_font = ui->Label_Nums->font();
    label_font.setPointSize(18);
    ui->Label_Nums->setFont(label_font);
    ui->Label_Server_isopen->setFont(label_font);
    ui->Label_Nums->setText(QString::number(0));

    showServerState(false);

    connect(ui->Btn_Client_Open, SIGNAL(clicked(bool)),this, SLOT(openNewClientWindow()));
    connect(ui->Btn_Server_Open, SIGNAL(clicked(bool)),m_tcpServer, SLOT(openServer()));
    connect(ui->Btn_Server_Close, SIGNAL(clicked(bool)),m_tcpServer, SLOT(closeServer()));
    connect(m_tcpServer, SIGNAL(showChatMessage(QString)), this, SLOT(serverReceiveMessage(QString)));
    connect(m_tcpServer, SIGNAL(changeClientNum(qint8)), this, SLOT(showClientNum(qint8)));
    connect(m_tcpServer, SIGNAL(sendServerState(bool)), this, SLOT(showServerState(bool)));
    connect(m_tcpServer, SIGNAL(sendServerState(bool)), this, SLOT(showServerState(bool)));

}

MainWindow::~MainWindow()
{
    delete ui;
    delete chat_model;
    delete m_tcpServer;
}

void MainWindow::openNewClientWindow()
{
    // 客户端未开启
    if(!m_tcpServer->isServerRunning()) {
        QMessageBox::warning(this, "错误", "请先启动服务端！");
        return;
    }

    //已达最大客户端数
    if (!m_tcpServer->isNumsMax()) {
        QMessageBox::warning(this, "提示", "线程池已满");
        return;
    }
    //发送信号量给客户端新建
    ChatClientWindow *client = new ChatClientWindow(this);
    client->setAttribute(Qt::WA_DeleteOnClose);//关闭窗口时消除指针
    client->show();  // 显示新窗口
}

void MainWindow::serverReceiveMessage(QString message)
{
    chat_content.append(message);
    chat_model->setStringList(chat_content);
    ui->Chatting_Box->setModel(chat_model);
    ui->Chatting_Box->show();

}

void MainWindow::showClientNum(qint8 nums)
{
    ui->Label_Nums->setText(QString::number(nums));
}

void MainWindow::showServerState(bool m_state)
{
    if(m_state == true)
        ui->Label_Server_isopen->setText("开");
    else
        ui->Label_Server_isopen->setText("关");
}










